package com.gwtcx.sample.serendipity.server.guice;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;

public class JpaGuiceModule extends AbstractModule {
    private static final ThreadLocal<EntityManager> ENTITY_MANAGER_CACHE = new ThreadLocal<EntityManager>();
    
    @Override
    protected void configure() {
    }

    @Provides
    @Singleton
    public EntityManagerFactory provideEntityManagerFactory() {
            return Persistence.createEntityManagerFactory("HSQLDB-HOSTED-xxx-PU");
    }
    
    @Provides
    public EntityManager provideEntityManager(EntityManagerFactory ef) {
            EntityManager em = ENTITY_MANAGER_CACHE.get();
            if(em == null) {
                    em = ef.createEntityManager();
                    ENTITY_MANAGER_CACHE.set(em);
            }
            return em;
    }
}